package com.exposit.books.service;

import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.exposit.books.dao.BuyerDAO;
import com.exposit.books.domain.Buyer;

@Service
@Transactional
public class LogInServiceImpl implements LogInService{

	@Autowired
	private BuyerDAO buyerDAO;

	@Override
	public Buyer logIn(String login, String password) throws Exception {
		Buyer buyer;
		if ((buyer = buyerDAO.getBuyerByLogin(login.toLowerCase())) == null)
			throw new Exception("Incorrect login!"); 
		if (buyer.getPassword().compareTo(password) != 0)
			throw new Exception("Incorrect password!");
		return buyer;
	}

	@Override
	public Buyer registration(String login, String password, String name, String surname) throws Exception {
		if (buyerDAO.getBuyerByLogin(login.toLowerCase()) != null)
			throw new Exception("User whith this login already exists.");
		Pattern p = Pattern.compile("^[A-Za-z]([\\.A-Za-z0-9-]{1,18})([A-Za-z0-9])$");
		if (!p.matcher(login).matches())
			throw new Exception("Invalid symbols in login.");
		if (login.length() < 4)
			throw new Exception("Login must contain at least 4 symbols.");
		if (password.length() < 6)
			throw new Exception("Password must contain at least 6 symbols.");
		if (name.length() < 2)
			throw new Exception("Name must contain at least 2 symbols.");
		if (surname.length() < 2)
			throw new Exception("Surname must contain at least 2 symbols.");
		p = Pattern.compile("[\\w&&[\\D&&[^_]]]{2,18}");
		if (!p.matcher(name).matches())
			throw new Exception("Uncorrect symbols in name.");
		if (!p.matcher(surname).matches())
			throw new Exception("Uncorrect symbols in surname.");
		char[] chars = name.toLowerCase().toCharArray();
		name = "";
		for (int i = 0; i<chars.length; i++)
		{
			if (i==0)
				name+=((Character) chars[i]).toString().toUpperCase();
			else
				name += chars[i];
		}
		chars = surname.toLowerCase().toCharArray();
		surname = "";
		for (int i = 0; i<chars.length; i++)
		{
			if (i==0)
				surname+=((Character) chars[i]).toString().toUpperCase();
			else
				surname += chars[i];
		}
		Buyer buyer = new Buyer(login.toLowerCase(), password, name, surname);
		buyerDAO.save(buyer);
		return buyer;
	}
	
}
